'######################################################################################
'Author  :         Sumit Gupta 
'Company :		     Vikasumit
'Date    :         1st August 2005
'Modify Date :     22nd September 2007
'--------------------------------------------------------------------------------------
'Working / Note on Class : 
'This is the Main Interface Drawing Class 
'It synchronize all the game play in one and the starting point of the application
'It consist of the BoardEngine and other GUI related stuffs
'
'18th Jan 2007
'Include LAN Game Feature
'Include option Box
'
'18th Feb 2007
'Found a bug that cause the LAN game to try make player offline on Internet Server (TODO)
'
'22nd September 2007
'Found a bug in piece position and notation :S
'######################################################################################

Imports VSChessEngine
Imports VSUtility
Imports System.Net
Imports System.Drawing
Imports System.Drawing.Drawing2D

Public Class frmMain
  Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

  Public Sub New()
    MyBase.New()

    'This call is required by the Windows Form Designer.
    InitializeComponent()

    'Add any initialization after the InitializeComponent() call

  End Sub

  'Form overrides dispose to clean up the component list.
  Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
    If disposing Then
      If Not (components Is Nothing) Then
        components.Dispose()
      End If
    End If
    MyBase.Dispose(disposing)
  End Sub

  'Required by the Windows Form Designer
  Private components As System.ComponentModel.IContainer

  'NOTE: The following procedure is required by the Windows Form Designer
  'It can be modified using the Windows Form Designer.  
  'Do not modify it using the code editor.
  Friend WithEvents PicMainBoard As System.Windows.Forms.PictureBox
  Friend WithEvents DefaultTheme As System.Windows.Forms.ImageList
  Friend WithEvents lstMove As System.Windows.Forms.ListView
  Friend WithEvents White As System.Windows.Forms.ColumnHeader
  Friend WithEvents Black As System.Windows.Forms.ColumnHeader
  Friend WithEvents mnuFile As System.Windows.Forms.MenuItem
  Friend WithEvents mnuFile_New As System.Windows.Forms.MenuItem
  Friend WithEvents mnuFile_sep1 As System.Windows.Forms.MenuItem
  Friend WithEvents mnuFile_CloseGame As System.Windows.Forms.MenuItem
  Friend WithEvents cntMnu_Main As System.Windows.Forms.ContextMenu
  Friend WithEvents mnuVisual As System.Windows.Forms.MenuItem
  Friend WithEvents mnuvisual_opacity As System.Windows.Forms.MenuItem
  Friend WithEvents picCutLog As System.Windows.Forms.PictureBox
  Friend WithEvents MenuItem3 As System.Windows.Forms.MenuItem
  Friend WithEvents mnuFile_Host As System.Windows.Forms.MenuItem
  Friend WithEvents mnuFile_Join As System.Windows.Forms.MenuItem
  Friend WithEvents MenuItem6 As System.Windows.Forms.MenuItem
  Friend WithEvents mnuFile_NetworkClose As System.Windows.Forms.MenuItem
  Friend WithEvents mnuvisual_background As System.Windows.Forms.MenuItem
  Friend WithEvents mnubackground_default As System.Windows.Forms.MenuItem
  Friend WithEvents mnubackground_red As System.Windows.Forms.MenuItem
  Friend WithEvents mnubackground_metal As System.Windows.Forms.MenuItem
  Friend WithEvents mnubackground_pink As System.Windows.Forms.MenuItem
  Friend WithEvents mnubackground_green As System.Windows.Forms.MenuItem
  Friend WithEvents mnubackground_blue As System.Windows.Forms.MenuItem
  Friend WithEvents mnubackground_rainbow As System.Windows.Forms.MenuItem
  Friend WithEvents mnuChessBoard As System.Windows.Forms.MenuItem
  Friend WithEvents mnuBoardDefault As System.Windows.Forms.MenuItem
  Friend WithEvents mnuBoardRed As System.Windows.Forms.MenuItem
  Friend WithEvents mnuBoardGreen As System.Windows.Forms.MenuItem
  Friend WithEvents mnuBoardBlack As System.Windows.Forms.MenuItem
  Friend WithEvents MenuItem8 As System.Windows.Forms.MenuItem
  Friend WithEvents MenuItem9 As System.Windows.Forms.MenuItem
  Friend WithEvents MenuItem10 As System.Windows.Forms.MenuItem
  Friend WithEvents mnuTools As System.Windows.Forms.MenuItem
  Friend WithEvents mnuOptions As System.Windows.Forms.MenuItem
  Friend WithEvents mnuHelp As System.Windows.Forms.MenuItem
  Friend WithEvents mnuAbout As System.Windows.Forms.MenuItem
  Friend WithEvents mnuVikasumit As System.Windows.Forms.MenuItem
    Friend WithEvents mnuGreenBrownie As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem1 As System.Windows.Forms.MenuItem
    Friend WithEvents mnuFile_LANHost As System.Windows.Forms.MenuItem
    Friend WithEvents mnuFile_LANJoin As System.Windows.Forms.MenuItem
    Friend WithEvents mnuFile_CloseLANGame As System.Windows.Forms.MenuItem
    Friend WithEvents MayaPiece As System.Windows.Forms.ImageList
    Friend WithEvents mnuChessPiece As System.Windows.Forms.MenuItem
    Friend WithEvents mnuPieceDefault As System.Windows.Forms.MenuItem
    Friend WithEvents mnuPieceMaya As System.Windows.Forms.MenuItem
    Friend WithEvents Sumidhi As System.Windows.Forms.ImageList
    Friend WithEvents kingdom As System.Windows.Forms.ImageList
    Friend WithEvents mnuPieceKingDom As System.Windows.Forms.MenuItem
    Friend WithEvents mnuPieceSumidhi As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem2 As System.Windows.Forms.MenuItem
    Friend WithEvents Lucena As System.Windows.Forms.ImageList
    Friend WithEvents mnnuTheme As System.Windows.Forms.MenuItem
    Friend WithEvents mnuThemeDefault As System.Windows.Forms.MenuItem
    Friend WithEvents mnuThemeBlackWhite As System.Windows.Forms.MenuItem
    Friend WithEvents mnuThemeSumidhi As System.Windows.Forms.MenuItem

    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmMain))
        Me.PicMainBoard = New System.Windows.Forms.PictureBox
        Me.DefaultTheme = New System.Windows.Forms.ImageList(Me.components)
        Me.lstMove = New System.Windows.Forms.ListView
        Me.White = New System.Windows.Forms.ColumnHeader
        Me.Black = New System.Windows.Forms.ColumnHeader
        Me.cntMnu_Main = New System.Windows.Forms.ContextMenu
        Me.mnuFile = New System.Windows.Forms.MenuItem
        Me.mnuFile_New = New System.Windows.Forms.MenuItem
        Me.mnuFile_sep1 = New System.Windows.Forms.MenuItem
        Me.mnuFile_Host = New System.Windows.Forms.MenuItem
        Me.mnuFile_Join = New System.Windows.Forms.MenuItem
        Me.MenuItem1 = New System.Windows.Forms.MenuItem
        Me.mnuFile_LANHost = New System.Windows.Forms.MenuItem
        Me.mnuFile_LANJoin = New System.Windows.Forms.MenuItem
        Me.MenuItem6 = New System.Windows.Forms.MenuItem
        Me.mnuFile_NetworkClose = New System.Windows.Forms.MenuItem
        Me.mnuFile_CloseLANGame = New System.Windows.Forms.MenuItem
        Me.mnuFile_CloseGame = New System.Windows.Forms.MenuItem
        Me.mnuTools = New System.Windows.Forms.MenuItem
        Me.mnuVisual = New System.Windows.Forms.MenuItem
        Me.mnuvisual_opacity = New System.Windows.Forms.MenuItem
        Me.MenuItem8 = New System.Windows.Forms.MenuItem
        Me.mnuvisual_background = New System.Windows.Forms.MenuItem
        Me.mnubackground_default = New System.Windows.Forms.MenuItem
        Me.mnubackground_red = New System.Windows.Forms.MenuItem
        Me.mnubackground_metal = New System.Windows.Forms.MenuItem
        Me.mnubackground_pink = New System.Windows.Forms.MenuItem
        Me.mnubackground_green = New System.Windows.Forms.MenuItem
        Me.mnubackground_blue = New System.Windows.Forms.MenuItem
        Me.mnubackground_rainbow = New System.Windows.Forms.MenuItem
        Me.mnuChessBoard = New System.Windows.Forms.MenuItem
        Me.mnuBoardDefault = New System.Windows.Forms.MenuItem
        Me.mnuBoardRed = New System.Windows.Forms.MenuItem
        Me.mnuBoardGreen = New System.Windows.Forms.MenuItem
        Me.mnuBoardBlack = New System.Windows.Forms.MenuItem
        Me.mnuGreenBrownie = New System.Windows.Forms.MenuItem
        Me.mnuChessPiece = New System.Windows.Forms.MenuItem
        Me.mnuPieceDefault = New System.Windows.Forms.MenuItem
        Me.mnuPieceMaya = New System.Windows.Forms.MenuItem
        Me.mnuPieceKingDom = New System.Windows.Forms.MenuItem
        Me.mnuPieceSumidhi = New System.Windows.Forms.MenuItem
        Me.MenuItem2 = New System.Windows.Forms.MenuItem
        Me.mnnuTheme = New System.Windows.Forms.MenuItem
        Me.mnuThemeDefault = New System.Windows.Forms.MenuItem
        Me.mnuThemeBlackWhite = New System.Windows.Forms.MenuItem
        Me.mnuThemeSumidhi = New System.Windows.Forms.MenuItem
        Me.MenuItem10 = New System.Windows.Forms.MenuItem
        Me.mnuOptions = New System.Windows.Forms.MenuItem
        Me.MenuItem9 = New System.Windows.Forms.MenuItem
        Me.mnuHelp = New System.Windows.Forms.MenuItem
        Me.mnuAbout = New System.Windows.Forms.MenuItem
        Me.MenuItem3 = New System.Windows.Forms.MenuItem
        Me.mnuVikasumit = New System.Windows.Forms.MenuItem
        Me.picCutLog = New System.Windows.Forms.PictureBox
        Me.MayaPiece = New System.Windows.Forms.ImageList(Me.components)
        Me.Sumidhi = New System.Windows.Forms.ImageList(Me.components)
        Me.kingdom = New System.Windows.Forms.ImageList(Me.components)
        Me.Lucena = New System.Windows.Forms.ImageList(Me.components)
        CType(Me.PicMainBoard, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.picCutLog, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'PicMainBoard
        '
        Me.PicMainBoard.Image = CType(resources.GetObject("PicMainBoard.Image"), System.Drawing.Image)
        Me.PicMainBoard.Location = New System.Drawing.Point(45, 45)
        Me.PicMainBoard.Name = "PicMainBoard"
        Me.PicMainBoard.Size = New System.Drawing.Size(384, 384)
        Me.PicMainBoard.TabIndex = 1
        Me.PicMainBoard.TabStop = False
        '
        'DefaultTheme
        '
        Me.DefaultTheme.ImageStream = CType(resources.GetObject("DefaultTheme.ImageStream"), System.Windows.Forms.ImageListStreamer)
        Me.DefaultTheme.TransparentColor = System.Drawing.Color.Transparent
        Me.DefaultTheme.Images.SetKeyName(0, "")
        Me.DefaultTheme.Images.SetKeyName(1, "")
        Me.DefaultTheme.Images.SetKeyName(2, "")
        Me.DefaultTheme.Images.SetKeyName(3, "")
        Me.DefaultTheme.Images.SetKeyName(4, "")
        Me.DefaultTheme.Images.SetKeyName(5, "")
        Me.DefaultTheme.Images.SetKeyName(6, "")
        Me.DefaultTheme.Images.SetKeyName(7, "")
        Me.DefaultTheme.Images.SetKeyName(8, "")
        Me.DefaultTheme.Images.SetKeyName(9, "")
        Me.DefaultTheme.Images.SetKeyName(10, "")
        Me.DefaultTheme.Images.SetKeyName(11, "")
        Me.DefaultTheme.Images.SetKeyName(12, "")
        '
        'lstMove
        '
        Me.lstMove.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
        Me.lstMove.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.White, Me.Black})
        Me.lstMove.FullRowSelect = True
        Me.lstMove.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable
        Me.lstMove.Location = New System.Drawing.Point(480, 280)
        Me.lstMove.MultiSelect = False
        Me.lstMove.Name = "lstMove"
        Me.lstMove.Size = New System.Drawing.Size(112, 144)
        Me.lstMove.TabIndex = 2
        Me.lstMove.UseCompatibleStateImageBehavior = False
        Me.lstMove.View = System.Windows.Forms.View.Details
        '
        'White
        '
        Me.White.Text = "White"
        Me.White.Width = 45
        '
        'Black
        '
        Me.Black.Text = "Black"
        Me.Black.Width = 47
        '
        'cntMnu_Main
        '
        Me.cntMnu_Main.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuFile, Me.mnuTools, Me.MenuItem9, Me.mnuHelp})
        '
        'mnuFile
        '
        Me.mnuFile.Index = 0
        Me.mnuFile.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuFile_New, Me.mnuFile_sep1, Me.mnuFile_Host, Me.mnuFile_Join, Me.MenuItem1, Me.mnuFile_LANHost, Me.mnuFile_LANJoin, Me.MenuItem6, Me.mnuFile_NetworkClose, Me.mnuFile_CloseLANGame, Me.mnuFile_CloseGame})
        Me.mnuFile.Text = "&Game"
        '
        'mnuFile_New
        '
        Me.mnuFile_New.Index = 0
        Me.mnuFile_New.Text = "&New Game"
        '
        'mnuFile_sep1
        '
        Me.mnuFile_sep1.Index = 1
        Me.mnuFile_sep1.Text = "-"
        '
        'mnuFile_Host
        '
        Me.mnuFile_Host.Index = 2
        Me.mnuFile_Host.Text = "Host Internet Game"
        '
        'mnuFile_Join
        '
        Me.mnuFile_Join.Index = 3
        Me.mnuFile_Join.Text = "Join Internet Game"
        '
        'MenuItem1
        '
        Me.MenuItem1.Index = 4
        Me.MenuItem1.Text = "-"
        '
        'mnuFile_LANHost
        '
        Me.mnuFile_LANHost.Index = 5
        Me.mnuFile_LANHost.Text = "Host LAN Game"
        '
        'mnuFile_LANJoin
        '
        Me.mnuFile_LANJoin.Index = 6
        Me.mnuFile_LANJoin.Text = "Join LAN Game"
        '
        'MenuItem6
        '
        Me.MenuItem6.Index = 7
        Me.MenuItem6.Text = "-"
        '
        'mnuFile_NetworkClose
        '
        Me.mnuFile_NetworkClose.Enabled = False
        Me.mnuFile_NetworkClose.Index = 8
        Me.mnuFile_NetworkClose.Text = "Close Network Game"
        '
        'mnuFile_CloseLANGame
        '
        Me.mnuFile_CloseLANGame.Enabled = False
        Me.mnuFile_CloseLANGame.Index = 9
        Me.mnuFile_CloseLANGame.Text = "Close LAN Game"
        '
        'mnuFile_CloseGame
        '
        Me.mnuFile_CloseGame.Index = 10
        Me.mnuFile_CloseGame.Text = "&Close Game"
        '
        'mnuTools
        '
        Me.mnuTools.Index = 1
        Me.mnuTools.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuVisual, Me.MenuItem10, Me.mnuOptions})
        Me.mnuTools.Text = "&Tools"
        '
        'mnuVisual
        '
        Me.mnuVisual.Index = 0
        Me.mnuVisual.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuvisual_opacity, Me.MenuItem8, Me.mnuvisual_background, Me.mnuChessBoard, Me.mnuChessPiece, Me.mnnuTheme})
        Me.mnuVisual.Text = "Visualizations"
        '
        'mnuvisual_opacity
        '
        Me.mnuvisual_opacity.Index = 0
        Me.mnuvisual_opacity.Text = "Opacity"
        '
        'MenuItem8
        '
        Me.MenuItem8.Index = 1
        Me.MenuItem8.Text = "-"
        '
        'mnuvisual_background
        '
        Me.mnuvisual_background.Index = 2
        Me.mnuvisual_background.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnubackground_default, Me.mnubackground_red, Me.mnubackground_metal, Me.mnubackground_pink, Me.mnubackground_green, Me.mnubackground_blue, Me.mnubackground_rainbow})
        Me.mnuvisual_background.Text = "BackGround"
        '
        'mnubackground_default
        '
        Me.mnubackground_default.Index = 0
        Me.mnubackground_default.Text = "Default"
        '
        'mnubackground_red
        '
        Me.mnubackground_red.Index = 1
        Me.mnubackground_red.Text = "Red"
        '
        'mnubackground_metal
        '
        Me.mnubackground_metal.Index = 2
        Me.mnubackground_metal.Text = "Metal"
        '
        'mnubackground_pink
        '
        Me.mnubackground_pink.Index = 3
        Me.mnubackground_pink.Text = "Pink"
        '
        'mnubackground_green
        '
        Me.mnubackground_green.Index = 4
        Me.mnubackground_green.Text = "Green"
        '
        'mnubackground_blue
        '
        Me.mnubackground_blue.Index = 5
        Me.mnubackground_blue.Text = "Blue"
        '
        'mnubackground_rainbow
        '
        Me.mnubackground_rainbow.Index = 6
        Me.mnubackground_rainbow.Text = "RainBow"
        '
        'mnuChessBoard
        '
        Me.mnuChessBoard.Index = 3
        Me.mnuChessBoard.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuBoardDefault, Me.mnuBoardRed, Me.mnuBoardGreen, Me.mnuBoardBlack, Me.mnuGreenBrownie})
        Me.mnuChessBoard.Text = "Chess Board"
        '
        'mnuBoardDefault
        '
        Me.mnuBoardDefault.Index = 0
        Me.mnuBoardDefault.Text = "Default"
        '
        'mnuBoardRed
        '
        Me.mnuBoardRed.Index = 1
        Me.mnuBoardRed.Text = "Red"
        '
        'mnuBoardGreen
        '
        Me.mnuBoardGreen.Index = 2
        Me.mnuBoardGreen.Text = "Greeny Red"
        '
        'mnuBoardBlack
        '
        Me.mnuBoardBlack.Index = 3
        Me.mnuBoardBlack.Text = "Black n White"
        '
        'mnuGreenBrownie
        '
        Me.mnuGreenBrownie.Index = 4
        Me.mnuGreenBrownie.Text = "Green Brownie"
        '
        'mnuChessPiece
        '
        Me.mnuChessPiece.Index = 4
        Me.mnuChessPiece.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuPieceDefault, Me.mnuPieceMaya, Me.mnuPieceKingDom, Me.mnuPieceSumidhi, Me.MenuItem2})
        Me.mnuChessPiece.Text = "Chess Piece"
        '
        'mnuPieceDefault
        '
        Me.mnuPieceDefault.Index = 0
        Me.mnuPieceDefault.Text = "Default"
        '
        'mnuPieceMaya
        '
        Me.mnuPieceMaya.Index = 1
        Me.mnuPieceMaya.Text = "Maya"
        '
        'mnuPieceKingDom
        '
        Me.mnuPieceKingDom.Index = 2
        Me.mnuPieceKingDom.Text = "Kingdom"
        '
        'mnuPieceSumidhi
        '
        Me.mnuPieceSumidhi.Index = 3
        Me.mnuPieceSumidhi.Text = "Sumidhi"
        '
        'MenuItem2
        '
        Me.MenuItem2.Index = 4
        Me.MenuItem2.Text = "Lucena"
        '
        'mnnuTheme
        '
        Me.mnnuTheme.Index = 5
        Me.mnnuTheme.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuThemeDefault, Me.mnuThemeBlackWhite, Me.mnuThemeSumidhi})
        Me.mnnuTheme.Text = "Theme"
        '
        'mnuThemeDefault
        '
        Me.mnuThemeDefault.Index = 0
        Me.mnuThemeDefault.Text = "Default"
        '
        'mnuThemeBlackWhite
        '
        Me.mnuThemeBlackWhite.Index = 1
        Me.mnuThemeBlackWhite.Text = "Black n White"
        '
        'mnuThemeSumidhi
        '
        Me.mnuThemeSumidhi.Index = 2
        Me.mnuThemeSumidhi.Text = "Sumidhi"
        '
        'MenuItem10
        '
        Me.MenuItem10.Index = 1
        Me.MenuItem10.Text = "-"
        '
        'mnuOptions
        '
        Me.mnuOptions.Index = 2
        Me.mnuOptions.Text = "Options"
        '
        'MenuItem9
        '
        Me.MenuItem9.Index = 2
        Me.MenuItem9.Text = "-"
        '
        'mnuHelp
        '
        Me.mnuHelp.Index = 3
        Me.mnuHelp.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuAbout, Me.MenuItem3, Me.mnuVikasumit})
        Me.mnuHelp.Text = "&Help"
        '
        'mnuAbout
        '
        Me.mnuAbout.Index = 0
        Me.mnuAbout.Text = "&About ChessMania"
        '
        'MenuItem3
        '
        Me.MenuItem3.Index = 1
        Me.MenuItem3.Text = "-"
        '
        'mnuVikasumit
        '
        Me.mnuVikasumit.Index = 2
        Me.mnuVikasumit.Text = "Vikasumit Online"
        '
        'picCutLog
        '
        Me.picCutLog.BackColor = System.Drawing.Color.White
        Me.picCutLog.Location = New System.Drawing.Point(475, 45)
        Me.picCutLog.Name = "picCutLog"
        Me.picCutLog.Size = New System.Drawing.Size(122, 190)
        Me.picCutLog.TabIndex = 3
        Me.picCutLog.TabStop = False
        '
        'MayaPiece
        '
        Me.MayaPiece.ImageStream = CType(resources.GetObject("MayaPiece.ImageStream"), System.Windows.Forms.ImageListStreamer)
        Me.MayaPiece.TransparentColor = System.Drawing.Color.Transparent
        Me.MayaPiece.Images.SetKeyName(0, "")
        Me.MayaPiece.Images.SetKeyName(1, "")
        Me.MayaPiece.Images.SetKeyName(2, "")
        Me.MayaPiece.Images.SetKeyName(3, "")
        Me.MayaPiece.Images.SetKeyName(4, "")
        Me.MayaPiece.Images.SetKeyName(5, "")
        Me.MayaPiece.Images.SetKeyName(6, "")
        Me.MayaPiece.Images.SetKeyName(7, "")
        Me.MayaPiece.Images.SetKeyName(8, "")
        Me.MayaPiece.Images.SetKeyName(9, "")
        Me.MayaPiece.Images.SetKeyName(10, "")
        Me.MayaPiece.Images.SetKeyName(11, "")
        Me.MayaPiece.Images.SetKeyName(12, "")
        '
        'Sumidhi
        '
        Me.Sumidhi.ImageStream = CType(resources.GetObject("Sumidhi.ImageStream"), System.Windows.Forms.ImageListStreamer)
        Me.Sumidhi.TransparentColor = System.Drawing.Color.Transparent
        Me.Sumidhi.Images.SetKeyName(0, "")
        Me.Sumidhi.Images.SetKeyName(1, "")
        Me.Sumidhi.Images.SetKeyName(2, "")
        Me.Sumidhi.Images.SetKeyName(3, "")
        Me.Sumidhi.Images.SetKeyName(4, "")
        Me.Sumidhi.Images.SetKeyName(5, "")
        Me.Sumidhi.Images.SetKeyName(6, "")
        Me.Sumidhi.Images.SetKeyName(7, "")
        Me.Sumidhi.Images.SetKeyName(8, "")
        Me.Sumidhi.Images.SetKeyName(9, "")
        Me.Sumidhi.Images.SetKeyName(10, "")
        Me.Sumidhi.Images.SetKeyName(11, "")
        '
        'kingdom
        '
        Me.kingdom.ImageStream = CType(resources.GetObject("kingdom.ImageStream"), System.Windows.Forms.ImageListStreamer)
        Me.kingdom.TransparentColor = System.Drawing.Color.Transparent
        Me.kingdom.Images.SetKeyName(0, "")
        Me.kingdom.Images.SetKeyName(1, "")
        Me.kingdom.Images.SetKeyName(2, "")
        Me.kingdom.Images.SetKeyName(3, "")
        Me.kingdom.Images.SetKeyName(4, "")
        Me.kingdom.Images.SetKeyName(5, "")
        Me.kingdom.Images.SetKeyName(6, "")
        Me.kingdom.Images.SetKeyName(7, "")
        Me.kingdom.Images.SetKeyName(8, "")
        Me.kingdom.Images.SetKeyName(9, "")
        Me.kingdom.Images.SetKeyName(10, "")
        Me.kingdom.Images.SetKeyName(11, "")
        '
        'Lucena
        '
        Me.Lucena.ImageStream = CType(resources.GetObject("Lucena.ImageStream"), System.Windows.Forms.ImageListStreamer)
        Me.Lucena.TransparentColor = System.Drawing.Color.Transparent
        Me.Lucena.Images.SetKeyName(0, "")
        Me.Lucena.Images.SetKeyName(1, "")
        Me.Lucena.Images.SetKeyName(2, "")
        Me.Lucena.Images.SetKeyName(3, "")
        Me.Lucena.Images.SetKeyName(4, "")
        Me.Lucena.Images.SetKeyName(5, "")
        Me.Lucena.Images.SetKeyName(6, "")
        Me.Lucena.Images.SetKeyName(7, "")
        Me.Lucena.Images.SetKeyName(8, "")
        Me.Lucena.Images.SetKeyName(9, "")
        Me.Lucena.Images.SetKeyName(10, "")
        Me.Lucena.Images.SetKeyName(11, "")
        '
        'frmMain
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.BackgroundImage = CType(resources.GetObject("$this.BackgroundImage"), System.Drawing.Image)
        Me.ClientSize = New System.Drawing.Size(640, 478)
        Me.ContextMenu = Me.cntMnu_Main
        Me.ControlBox = False
        Me.Controls.Add(Me.picCutLog)
        Me.Controls.Add(Me.lstMove)
        Me.Controls.Add(Me.PicMainBoard)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.MaximizeBox = False
        Me.MinimizeBox = False
        Me.Name = "frmMain"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "VsChessMania v2 "
        CType(Me.PicMainBoard, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.picCutLog, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)

    End Sub

#End Region

#Region "Private Declarations"

    Private Const WM_NCHITTEST As Integer = &H84
    Private Const HTCLIENT As Integer = &H1
    Private Const HTCAPTION As Integer = &H2

    Dim WithEvents BoardEngine As clsGameEngine
    Dim Board_Bitmap As Bitmap 'Default Chess Background
    Dim mousepos As clsPosition 'Mouse Position in board
    Dim Log As clsLog
    Dim CurrentPieceGraphics As String = "Default"

    'Network Game
    Dim WithEvents NServer As clsServer
    Dim WithEvents NClient As clsClient

    Dim IsNetworkGame As Boolean = False
    Dim IsNetworkClient As Boolean = False

#End Region

#Region "Form General Events"

    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        Select Case m.Msg
            Case WM_NCHITTEST
                MyBase.WndProc(m)
                If (m.Result.ToInt32 = HTCLIENT) Then
                    m.Result = IntPtr.op_Explicit(HTCAPTION)
                End If
                Exit Sub
        End Select
        MyBase.WndProc(m)
    End Sub

    Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        LoadConfiguration()
        Log = New clsLog("TempMain" + DateTime.Now.Millisecond.ToString(), "1")
        Log.AddDateTimeStamp = True
        Log.DoLogging = True
        Log.Write("Start Game GUI")
        mousepos = New clsPosition
        BoardEngine = New clsGameEngine
        BoardEngine.StartNewGame()
        BoardEngine.DoLogging = False
        Try
            Board_Bitmap = New Bitmap(MyPath & "\images\board_1.png") 'Set the Background image 
        Catch ex As IO.IOException
            MsgBox("File Read Error Please Check the Installation Guide for the Required Files" & _
            vbCrLf & vbCrLf & "Following Error has occur during the Game StartUp Process : " & vbCrLf & _
            ex.Message & vbCrLf & "--------------Closing Application-------------")
            SaveSettings()
            EndApplication()
        End Try
        Log.Write("Bitmap loaded")
    End Sub

#End Region

#Region "Board Rendering Related"

    Private Sub PicMainBoard_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PicMainBoard.MouseUp
        Dim x, y As Integer
        'Map Case Number clicked
        x = CInt(Int(e.X / 48))
        y = CInt(Int(e.Y / 48))

        If x > 7 Then x = 7
        If y > 7 Then y = 7
        If x < 0 Then x = 0
        If y < 0 Then y = 0
        mousepos = New clsPosition(y, x)

        'Check the network Game and if move is allowed or not ;o)
        If Me.IsNetworkGame Then
            If Me.IsNetworkClient Then
                If BoardEngine.MoveOf = enPieceColor.PCBlack Then
                    If BoardEngine.MakeMove(mousepos) Then
                        MainBoardRefresh()
                        Log.Write("Move OK")
                    Else
                        Log.Write("Invalid move")
                    End If
                End If
            Else
                If RemoveMessageBox Then
                    If BoardEngine.MoveOf = enPieceColor.PCWhite Then
                        If BoardEngine.MakeMove(mousepos) Then
                            MainBoardRefresh()
                            Log.Write("Move OK")
                        Else
                            Log.Write("Invalid move")
                        End If
                    End If
                End If
            End If
        Else
            If BoardEngine.MakeMove(mousepos) Then
                MainBoardRefresh()
                Log.Write("Move OK")
            Else
                Log.Write("Invalid move")
            End If
        End If

    End Sub

    Private Sub PicMainBoard_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PicMainBoard.MouseMove
        Static x, y As Integer
        'Map Case Number clicked
        If (Int(e.X / 48) = x) And (y = Int(e.Y / 48)) Then
            Exit Sub
        Else
            x = CInt(Int(e.X / 48))
            y = CInt(Int(e.Y / 48))
            If x > 7 Then x = 7
            If y > 7 Then y = 7
            If x < 0 Then x = 0
            If y < 0 Then y = 0
            mousepos = New clsPosition(y, x)
            MainBoardRefresh()
        End If
    End Sub

    Private Function GetPieceBitMap(ByVal PieceId As Integer) As Bitmap
        Dim b As Bitmap

        Select Case (CurrentPieceGraphics)
            Case "Default"
                b = New Bitmap(DefaultTheme.Images.Item(PieceId))
                b.MakeTransparent(Color.White)
            Case "Maya"
                b = New Bitmap(MayaPiece.Images.Item(PieceId))
            Case "Kingdom"
                b = New Bitmap(kingdom.Images.Item(PieceId))
                b.MakeTransparent(Color.White)
            Case "Sumidhi"
                b = New Bitmap(Sumidhi.Images.Item(PieceId))
            Case "Lucena"
                b = New Bitmap(Lucena.Images.Item(PieceId))
                b.MakeTransparent(Color.White)
            Case Else
                b = New Bitmap(DefaultTheme.Images.Item(PieceId))
                b.MakeTransparent(Color.White)
        End Select
        Return b
    End Function

    'Function to retrun the Piece Id in Image list
    Private Function GetPieceId(ByVal Piece As clsPiece) As Integer
        Log.Write("GetPieceId Called")
        Select Case Piece.Type
            Case enPieceType.PTBishop
                If Piece.Color = enPieceColor.PCBlack Then
                    Return 0
                Else
                    Return 6
                End If
            Case enPieceType.PTCounselor
                If Piece.Color = enPieceColor.PCBlack Then
                    Return 1
                Else
                    Return 7
                End If
            Case enPieceType.PTKing
                If Piece.Color = enPieceColor.PCBlack Then
                    Return 2
                Else
                    Return 8
                End If
            Case enPieceType.PTKnight
                If Piece.Color = enPieceColor.PCBlack Then
                    Return 3
                Else
                    Return 9
                End If
            Case enPieceType.PTPawn
                If Piece.Color = enPieceColor.PCBlack Then
                    Return 4
                Else
                    Return 10
                End If
            Case enPieceType.PTRook
                If Piece.Color = enPieceColor.PCBlack Then
                    Return 5
                Else
                    Return 11
                End If
        End Select
    End Function

    'Function to Render the board with Background Image
    Private Sub RenderCompleteBoard(ByVal G As Graphics)
        Log.Write("RenderCompleteBoard Called")
        Dim r As New Rectangle(0, 0, 386, 386)
        G.DrawImage(Board_Bitmap, r, 0, 0, 386, 386, GraphicsUnit.Pixel)
        Render(G)
    End Sub

    'Private Sub to render the board without Background Image
    Private Sub Render(ByVal g As Graphics)
        Dim r As Rectangle
        Dim i, j As Integer
        Dim piece As Bitmap
        For i = 0 To 7
            For j = 0 To 7
                Log.Write("Render() :: In the For with i:: " & i & " and j :: " & j)
                If (mousepos.Y = i And mousepos.X = j) Then
                    piece = New Bitmap(MyPath & "\Images\grey.bmp")
                    piece.MakeTransparent(Color.White)
                    r = New Rectangle(48 * i, 48 * j, 48, 48)
                    g.DrawImage(piece, r, 0, 0, 48, 48, GraphicsUnit.Pixel)
                    Log.Write("In the first if")
                End If
                'if there is a piece at position than draw that on board

                If Not BoardEngine.ReadBoard(j, i).IsNull Then

                    Log.Write("Piece is not Null . Piece type is ::" & BoardEngine.ReadBoard(j, i).Type.ToString)
                    Log.Write("BoardEngine.SelectedPiece.Type is ::" & BoardEngine.SelectedPiece.Type.ToString)
                    Log.Write("BoardEngine.SelectedPiecePosition.X ::" & BoardEngine.SelectedPiecePosition.X)
                    Log.Write("BoardEngine.ReadBoard(j, i).Color ::" & BoardEngine.ReadBoard(j, i).Color.ToString)
                    Log.Write("BoardEngine.SelectedPiece.Color ::" & BoardEngine.SelectedPiece.Color.ToString)
                    Log.Write("J ::" & j & " i ::" & i)

                    'A Piece is selected
                    If (BoardEngine.ReadBoard(j, i).Type = BoardEngine.SelectedPiece.Type) And _
                    (BoardEngine.ReadBoard(j, i).Color = BoardEngine.SelectedPiece.Color) And _
                    j = BoardEngine.SelectedPiecePosition.X And i = BoardEngine.SelectedPiecePosition.Y Then
                        piece = New Bitmap(MyPath & "\images\selection.bmp")
                        piece.MakeTransparent(Color.White)
                        r = New Rectangle(48 * i, 48 * j, 48, 48)
                        g.DrawImage(piece, r, 0, 0, 48, 48, GraphicsUnit.Pixel)
                    End If
                    Log.Write("In the Out of Third if")
                    piece = GetPieceBitMap(GetPieceId(BoardEngine.ReadBoard(j, i)))
                    r = New Rectangle(48 * i, 48 * j, 48, 48)
                    g.DrawImage(piece, r, 0, 0, 48, 48, GraphicsUnit.Pixel)
                End If
            Next
        Next
        Log.Write("Out of For Loop in Render Function")
    End Sub

    Public Function ToNotation(ByVal pos As clsPosition) As String
        Dim rtn As String
        Select Case pos.Y
            Case 0
                rtn = "a"
            Case 1
                rtn = "b"
            Case 2
                rtn = "c"
            Case 3
                rtn = "d"
            Case 4
                rtn = "e"
            Case 5
                rtn = "f"
            Case 6
                rtn = "g"
            Case 7
                rtn = "h"
            Case Else
                rtn = "z" 'error case
        End Select
        Return (rtn & (pos.X + 1).ToString)
    End Function

    Private Sub PicMainBoard_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PicMainBoard.Paint
        RenderCompleteBoard(e.Graphics)
    End Sub

#End Region

#Region "ThreadSafe Function"

    'REMARK: Code for Thread Safe functions

    Delegate Sub BoardRefreshCallBack()
    Delegate Sub MessageHideCallBack()
    Delegate Sub MoveListAddCallBack(ByVal SubList As Boolean, ByVal Move As String)
    Delegate Sub CutLogRefreshCallBack()
    Delegate Sub ClearMoveListCallBack()

    'Clear Move Log Thread Safe
    Private Sub ClearMoveListCallSafe()
        lstMove.Items.Clear()
    End Sub

    Private Sub ClearMoveList()
        If lstMove.InvokeRequired Then
            Dim d As New ClearMoveListCallBack(AddressOf ClearMoveListCallSafe)
            lstMove.Invoke(d, New Object() {})
        Else
            ClearMoveListCallSafe()
        End If
    End Sub

    'Cut Log Refresh
    Private Sub CutLogRefreshCallSafe()
        picCutLog.Refresh()
    End Sub

    Private Sub CutLogRefersh()
        If picCutLog.InvokeRequired Then
            Dim d As New CutLogRefreshCallBack(AddressOf CutLogRefreshCallSafe)
            picCutLog.Invoke(d, New Object() {})
        Else
            picCutLog.Refresh()
        End If
    End Sub


    'ListAdd
    Private Sub MoveListCallSafe(ByVal SubList As Boolean, ByVal Move As String)
        If SubList Then
            lstMove.Items(lstMove.Items.Count - 1).SubItems.Add(Move)
        Else
            lstMove.Items.Add(Move)
        End If
    End Sub

    Private Sub MoveList(ByVal SubList As Boolean, ByVal Move As String)
        If lstMove.InvokeRequired Then
            Dim d As New MoveListAddCallBack(AddressOf MoveListCallSafe)
            PicMainBoard.Invoke(d, New Object() {SubList, Move})
        Else
            MoveListCallSafe(SubList, Move)
        End If
    End Sub

    'BoardRefreshCallSafe
    Private Sub BoardRefreshCallSafe()
        PicMainBoard.Refresh()
    End Sub

    Private Sub MainBoardRefresh()
        If PicMainBoard.InvokeRequired Then
            Dim d As New BoardRefreshCallBack(AddressOf BoardRefreshCallSafe)
            PicMainBoard.Invoke(d, New Object() {})
        Else
            PicMainBoard.Refresh()
        End If
    End Sub


    Private Sub MessageHide()
        frmMsg.Hide()
    End Sub

#End Region

    Private Sub BoardEngine_MoveCommited(ByVal movedata As String) Handles BoardEngine.MoveCommited
        Try
            My.Computer.Audio.Stop()
            My.Computer.Audio.Play(AppConfig.GetValue("Sound", "MoveCommitted"))
        Catch ex As Exception
        End Try
        Dim sData() As String
        Dim move As String
        Log.Write("In BoardEngine_MoveCommited " + movedata)
        sData = movedata.Split(CChar("-"))
        move = ToNotation(New clsPosition(CInt(Mid(sData(0), 1, 1)), CInt(Mid(sData(0), 2, 1))))
        move &= "-" & ToNotation(New clsPosition(CInt(Mid(sData(1), 1, 1)), CInt(Mid(sData(1), 2, 1))))
        If BoardEngine.MoveOf.ToString = "PCWhite" Then
            MoveList(True, move)
            'lstMove.Items(lstMove.Items.Count - 1).SubItems.Add(move)
        ElseIf BoardEngine.MoveOf.ToString = "PCBlack" Then
            'lstMove.Items.Add(move)
            MoveList(False, move)
        End If

        CutLogRefersh() 'Call for the Cut Log
        'Check for Network game here and if so send the move..:)
        'Network Transfer Format is Messagetype|move ex 0|e2-e4
        If Me.IsNetworkGame Then
            move = MessageType.Move & "|" & move
            If Me.IsNetworkClient Then
                NClient.SendData(move)
            Else
                NServer.SendData(move)
            End If
        End If
    End Sub

    Private Sub BoardEngine_PawnPromoted(ByVal PieceColor As String) Handles BoardEngine.PawnPromoted
        BoardEngine.PromotePawn(enPieceType.PTCounselor)
        Try
            My.Computer.Audio.Stop()
            My.Computer.Audio.Play(AppConfig.GetValue("Sound", "PawnPromotion"))
        Catch ex As Exception
        End Try
    End Sub

    Private Sub BoardEngine_PieceCut(ByVal piece As VSChessEngine.clsPiece) Handles BoardEngine.PieceCut
        Try
            My.Computer.Audio.Stop()
            My.Computer.Audio.Play(AppConfig.GetValue("Sound", "PawnCut"))
        Catch ex As Exception
        End Try
    End Sub

    Private Sub mnuFile_CloseGame_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFile_CloseGame.Click
        If Me.IsNetworkGame Then
            If Me.IsNetworkClient Then
                NClient.CloseConnection()
            Else
                NServer.CloseConnection()
                MakeMeOffline(PlayerWhite)
            End If
        End If
        SaveSettings()
        EndApplication()
    End Sub

    'Private Sub to render the board without Background Image
    Private Sub RenderCutLog(ByVal g As Graphics)
        Dim r As Rectangle
        Dim i As Integer
        Dim Blackpos, whitepos, Bctr, Wctr As Integer
        Bctr = 0
        Wctr = 0
        Blackpos = 0
        whitepos = 2
        Dim piece As Bitmap
        For i = 0 To 31
            If Not BoardEngine.CutLog(i).IsNull Then
                piece = GetPieceBitMap(GetPieceId(BoardEngine.CutLog(i)))
                If BoardEngine.CutLog(i).Color = enPieceColor.PCBlack Then
                    r = New Rectangle(24 * Blackpos, 24 * (Bctr Mod 8), 24, 24)
                    g.DrawImage(piece, r, 0, 0, 48, 48, GraphicsUnit.Pixel)
                    If Bctr >= 7 Then Blackpos = 1
                    Bctr += 1
                ElseIf BoardEngine.CutLog(i).Color = enPieceColor.PCWhite Then
                    r = New Rectangle(24 * whitepos, 24 * (Wctr Mod 8), 24, 24)
                    g.DrawImage(piece, r, 0, 0, 48, 48, GraphicsUnit.Pixel)
                    If Wctr >= 7 Then whitepos = 3
                    Wctr += 1
                End If
            End If
        Next
    End Sub

    Private Sub picCutLog_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles picCutLog.Paint
        RenderCutLog(e.Graphics)
    End Sub

    Private Sub mnuvisual_opacity_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuvisual_opacity.Click
        Dim frm As New frmOpacityBar
        frm.OpacityValue = CInt(Me.Opacity * 100)
        frm.ShowDialog()
        Me.Opacity = (frm.OpacityValue / 100)
        Me.Refresh()
    End Sub

    Private Sub mnuFile_New_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFile_New.Click
        NewGame()
    End Sub

    Private Sub NewGame()
        mousepos = New clsPosition
        BoardEngine = New clsGameEngine

        Dim defaultName As String = AppConfig.GetValue("GamePlay", "DefaultName")
        If Me.IsNetworkGame Then
            If Me.IsNetworkClient Then
                PlayerBlack = InputBox("Please Enter your Name (Black Player)", Application.ProductName, defaultName)
            Else
                PlayerWhite = InputBox("Please Enter your Name (White Player)", Application.ProductName, defaultName)
            End If
        Else
            PlayerWhite = InputBox("Please Enter your Name (White Player)", Application.ProductName, defaultName)
            PlayerBlack = InputBox("Please Enter your Name (Black Player)", Application.ProductName)
        End If

        BoardEngine.StartNewGame()
        BoardEngine.DoLogging = False
        ClearMoveList()
        CutLogRefersh()
        MainBoardRefresh()
    End Sub

    Private Sub btnmin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.WindowState = FormWindowState.Minimized
    End Sub

    Private Sub btnclose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        SaveSettings()
        EndApplication()
    End Sub

    'Vikasumit Site
    Private Sub MenuItem4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuVikasumit.Click
        Process.Start("http://www.vikasumit.com")
    End Sub

    'About Box
    Private Sub mnuAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAbout.Click
        Dim frm As New frmAbout
        frm.ShowDialog()
    End Sub

    Private Sub frmMain_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Resize
        Me.WindowState = FormWindowState.Normal
    End Sub

    Private Sub LoadConfiguration()
        Dim tmpvalue As String
        tmpvalue = AppConfig.GetValue("Display", "Opacity")
        If tmpvalue = "FALSE" OrElse Not IsNumeric(tmpvalue) OrElse CInt(tmpvalue) < 0 OrElse CInt(tmpvalue) > 1 Then
            Me.Opacity = 0.75
        Else
            Me.Opacity = CSng(tmpvalue)
        End If
    End Sub

    Private Sub SaveSettings()
        AppConfig.SetValue("Display", "Opacity", CStr(Me.Opacity))
    End Sub

    Private Sub DataRecieved(ByVal data As String)
        'modify this function display the Move and do extra stuff for network game play
        'Data is in Format MessageType|data

        Log.Write("In DataRecieved " + data)
        Dim SplitData() As String
        SplitData = data.Split(CChar("|"))
        Select Case SplitData(0)
            Case MessageType.Move
                MakeMove(SplitData(1))
            Case MessageType.Board
                'Change the Board
            Case MessageType.Closing
                MsgBox("Your Partner has request to close the game." & vbCrLf & "You are the winner now. Click Ok to End existing game")
                NewGame()
            Case Else
                'Invalid Data Recieved
        End Select
    End Sub

    'Function to Commit the Move Recieved from Network
    Private Sub MakeMove(ByVal data As String)
        Dim Moves() As String
        Dim Pos As clsPosition
        Pos = New clsPosition
        Moves = data.Split(CChar("-"))
        Pos.X = CInt(CInt(Mid(Moves(0), 2, 1)) - 1)
        Pos.Y = ConvertStringtoInt(Mid(Moves(0), 1, 1))
        If BoardEngine.MakeMove(Pos) Then
            MainBoardRefresh()
        Else
            'Do Nothing Right now
        End If
        Pos = New clsPosition
        Pos.X = CInt(CInt(Mid(Moves(1), 2, 1)) - 1)
        Pos.Y = ConvertStringtoInt(Mid(Moves(1), 1, 1))
        If BoardEngine.MakeMove(Pos) Then
            MainBoardRefresh()
        Else
            'Do Nothing Right now
        End If
    End Sub

    Private Sub NServer_DataRecieved(ByVal Data As String) Handles NServer.DataRecieved
        Dim msg As String
        msg = NServer.GetInput
        DataRecieved(msg)
    End Sub

    Private Sub NClient_DataRecieve(ByVal Data As String) Handles NClient.DataRecieve
        Dim msg As String
        msg = NClient.GetInput
        DataRecieved(msg)
    End Sub

    Private Sub frmMain_SizeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.SizeChanged
        Me.WindowState = FormWindowState.Normal
    End Sub

    Private Sub mnuFile_Host_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFile_Host.Click
        Me.IsNetworkGame = True
        Me.IsNetworkClient = False
        NServer = New clsServer
        NServer.IPAddr = IPAddress.Parse("0.0.0.0")
        NServer.Port = CInt(AppConfig.GetValue("Settings", "Port"))
        NewGame()
        If NServer.StartServer() Then
            DisableNetworkMenuButThis("INTERNET")
            MakeMeOnline(PlayerWhite)
        Else
            EnableNetworkMenu()
            Me.IsNetworkGame = False
            Me.IsNetworkClient = True
        End If
    End Sub

    Private Sub mnuFile_Join_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFile_Join.Click
        NClient = New clsClient

        Me.IsNetworkGame = True
        Me.IsNetworkClient = True

        Dim frmIp As New frmIPlist
        frmIp.ShowDialog()
        If Not frmIp.IPAddr = Nothing Then
            NClient.IPAddr = IPAddress.Parse(frmIp.IPAddr)
            NClient.Port = frmIp.IPPort
            NewGame()
            If NClient.StartClient() Then
                DisableNetworkMenuButThis("INTERNET")
            Else
                EnableNetworkMenu()
                Me.IsNetworkGame = False
                Me.IsNetworkClient = False
                MsgBox("Fail to Join the Game Host on IP Address " & NClient.IPAddr.ToString)
            End If
        Else
            EnableNetworkMenu()
            Me.IsNetworkGame = False
            Me.IsNetworkClient = False
            MsgBox("Unable to Detect the Host IP")
        End If
    End Sub

    Private Sub mnuFile_NetworkClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFile_NetworkClose.Click
        If Me.IsNetworkGame Then
            If Me.IsNetworkClient Then
                NClient.SendData(MessageType.Closing & "|CLOSING")
                NClient.CloseConnection()
            Else
                NServer.SendData(MessageType.Closing & "|CLOSING")
                NServer.CloseConnection()
                MakeMeOffline(PlayerWhite)
            End If
        End If
        Me.IsNetworkClient = False
        Me.IsNetworkGame = False
        SaveSettings()
        EnableNetworkMenu()
    End Sub

    Private Sub NServer_ServerSetupMessage(ByVal msg As String, ByVal msgNo As Integer) Handles NServer.ServerSetupMessage
        If msgNo = 11005 Then
            frmMsg.Message = msg
            frmMsg.MessageNo = msgNo.ToString
            frmMsg.Show()
            RemoveMessageBox = False
        End If
    End Sub

    Private Sub NServer_ClientAccepted() Handles NServer.ClientAccepted
        MakeMeOffline(PlayerWhite)
        RemoveMessageBox = True
        If (frmMsg.InvokeRequired) Then
            Dim d As New MessageHideCallBack(AddressOf MessageHide)
            frmMsg.Invoke(d, New Object() {})
        Else
            frmMsg.Hide()
        End If

    End Sub

    Private Sub BoardEngine_GameEnd(ByVal loser As VSChessEngine.enPieceColor) Handles BoardEngine.GameEnd
        Dim winner As String
        If loser = enPieceColor.PCBlack Then
            winner = "White"
        Else
            winner = "Black"
        End If
        MsgBox("Game Ends and the winner is " & winner)
    End Sub

    Private Sub frmMain_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Activated
        If Not RemoveMessageBox And Me.IsNetworkGame Then
            frmMsg.Show()
            frmMsg.Focus()
        End If
    End Sub

    Private Sub NServer_ServerClosed() Handles NServer.ServerClosed
        RemoveMessageBox = True
        frmMsg.Hide()
    End Sub

    Private Sub NClient_ClientSetupMessage(ByVal msg As String, ByVal msgNo As Integer) Handles NClient.ClientSetupMessage
        MsgBox(msg)
    End Sub

    Private Sub NClient_ClientSetupError(ByVal msg As String, ByVal msgNo As Integer) Handles NClient.ClientSetupError
        MsgBox(msg & vbCrLf & msgNo)
    End Sub

    Private Sub frmMain_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.GotFocus
        If Not RemoveMessageBox And Me.IsNetworkGame Then
            frmMsg.Show()
            frmMsg.Focus()
        ElseIf Me.IsNetworkGame And RemoveMessageBox Then
            frmMsg.Hide()
        End If
    End Sub

#Region "Background loader"

    Private Sub mnubackground_default_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnubackground_default.Click
        Try
            Me.BackgroundImage = New Bitmap(MyPath & "\images\ui_blackwhite.png") 'Set the Background image 
            Me.Refresh()
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
    End Sub

    Private Sub mnubackground_red_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnubackground_red.Click
        Try
            Me.BackgroundImage = New Bitmap(MyPath & "\images\ui_red.png") 'Set the Background image 
            Me.Refresh()
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
    End Sub

    Private Sub mnubackground_metal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnubackground_metal.Click
        Try
            Me.BackgroundImage = New Bitmap(MyPath & "\images\ui_metal.png") 'Set the Background image 
            Me.Refresh()
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
    End Sub

    Private Sub mnubackground_pink_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnubackground_pink.Click
        Try
            Me.BackgroundImage = New Bitmap(MyPath & "\images\ui_pink.png") 'Set the Background image 
            Me.Refresh()
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
    End Sub

    Private Sub mnubackground_green_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnubackground_green.Click
        Try
            Me.BackgroundImage = New Bitmap(MyPath & "\images\ui_green.png") 'Set the Background image 
            Me.Refresh()
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
    End Sub

    Private Sub mnubackground_blue_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnubackground_blue.Click
        Try
            Me.BackgroundImage = New Bitmap(MyPath & "\images\ui_blue.png") 'Set the Background image 
            Me.Refresh()
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
    End Sub

    Private Sub mnubackground_rainbow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnubackground_rainbow.Click
        Try
            Me.BackgroundImage = New Bitmap(MyPath & "\images\ui_rainbow.png") 'Set the Background image 
            Me.Refresh()
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
    End Sub
#End Region

#Region "Board Graphics"

    Private Sub mnuBoardBlack_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuBoardBlack.Click
        Try
            Board_Bitmap = New Bitmap(MyPath & "\images\board_4.png")
            MainBoardRefresh()
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
    End Sub

    Private Sub mnuBoardDefault_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuBoardDefault.Click
        Try
            Board_Bitmap = New Bitmap(MyPath & "\images\board_1.png")
            MainBoardRefresh()
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
    End Sub

    Private Sub mnuBoardGreen_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuBoardGreen.Click
        Try
            Board_Bitmap = New Bitmap(MyPath & "\images\board_3.png")
            MainBoardRefresh()
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
    End Sub

    Private Sub mnuBoardRed_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuBoardRed.Click
        Try
            Board_Bitmap = New Bitmap(MyPath & "\images\board_2.png")
            MainBoardRefresh()
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
    End Sub

    Private Sub mnuGreenBrownie_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuGreenBrownie.Click
        Try
            Board_Bitmap = New Bitmap(MyPath & "\images\board_5.png")
            MainBoardRefresh()
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
    End Sub

#End Region

    Private Sub mnuOptions_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuOptions.Click
        Dim frmoptions As New frmOption
        frmoptions.OpacityValue = CInt(Me.Opacity * 100)
        frmoptions.ShowDialog()
        Me.Opacity = (frmoptions.OpacityValue / 100)
        Me.Refresh()
    End Sub

    Private Sub mnuFile_LANHost_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFile_LANHost.Click
        Dim frm As New frmLanHost
        Dim PortToUse As Integer
        frm.ShowDialog()
        If frm.DialogResult = Windows.Forms.DialogResult.OK Then
            PortToUse = frm.Port
        End If
        Me.IsNetworkGame = True
        Me.IsNetworkClient = False
        NServer = New clsServer
        NServer.IPAddr = IPAddress.Parse("0.0.0.0")
        NServer.Port = PortToUse
        NewGame()
        If NServer.StartServer() Then
            DisableNetworkMenuButThis("LAN")
        Else
            EnableNetworkMenu()
        End If
    End Sub

    Private Sub EnableNetworkMenu()
        'Function to enable NetworkMenu for Game Play
        mnuFile_New.Enabled = True
        mnuFile_Join.Enabled = True
        mnuFile_Host.Enabled = True
        mnuFile_LANJoin.Enabled = True
        mnuFile_LANHost.Enabled = True
        mnuFile_NetworkClose.Enabled = False
        mnuFile_CloseLANGame.Enabled = False
    End Sub

    Private Sub DisableNetworkMenuButThis(ByVal enableme As String)
        'Enable just required menu and disable all
        mnuFile_New.Enabled = False
        mnuFile_Join.Enabled = False
        mnuFile_Host.Enabled = False
        mnuFile_LANJoin.Enabled = False
        mnuFile_LANHost.Enabled = False
        If enableme = "LAN" Then
            mnuFile_NetworkClose.Enabled = False
            mnuFile_CloseLANGame.Enabled = True
        Else
            mnuFile_NetworkClose.Enabled = True
            mnuFile_CloseLANGame.Enabled = False
        End If
    End Sub

    Private Sub mnuFile_LANJoin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFile_LANJoin.Click
        NClient = New clsClient

        Me.IsNetworkGame = True
        Me.IsNetworkClient = True

        Dim frmIp As New frmLANJoin
        frmIp.ShowDialog()
        If Not frmIp.IPAddr = Nothing OrElse frmIp.IPAddr.ToString <> "0.0.0.0" Then
            NClient.IPAddr = IPAddress.Parse(frmIp.IPAddr)
            NClient.Port = CInt(frmIp.IPPort)
            NewGame()
            If NClient.StartClient() Then
                DisableNetworkMenuButThis("LAN")
            Else
                EnableNetworkMenu()
                Me.IsNetworkGame = False
                Me.IsNetworkClient = False

                MsgBox("Fail to Join the Game Host on IP Address " & NClient.IPAddr.ToString)
            End If
        Else
            EnableNetworkMenu()
            Me.IsNetworkGame = False
            Me.IsNetworkClient = False

            MsgBox("Unable to Detect the Host IP or You have cancel the Join operation." & vbCrLf & "Starting a New Game for you")
            NewGame()
        End If
    End Sub

    Private Sub mnuFile_CloseLANGame_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFile_CloseLANGame.Click
        If Me.IsNetworkGame Then
            If Me.IsNetworkClient Then
                NClient.SendData(MessageType.Closing & "|CLOSING")
                NClient.CloseConnection()
            Else
                NServer.SendData(MessageType.Closing & "|CLOSING")
                NServer.CloseConnection()
            End If
        End If
        Me.IsNetworkClient = False
        Me.IsNetworkGame = False
        SaveSettings()

        EnableNetworkMenu()
    End Sub

    Private Sub mnuPieceDefault_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuPieceDefault.Click
        CurrentPieceGraphics = "Default"
        MainBoardRefresh()
    End Sub

    Private Sub mnuPieceMaya_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuPieceMaya.Click
        CurrentPieceGraphics = "Maya"
        MainBoardRefresh()
    End Sub

    Private Sub mnuPieceKingDom_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuPieceKingDom.Click
        CurrentPieceGraphics = "Kingdom"
        MainBoardRefresh()
    End Sub

    Private Sub mnuPieceSumidhi_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuPieceSumidhi.Click
        CurrentPieceGraphics = "Sumidhi"
        MainBoardRefresh()
    End Sub

    Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click
        CurrentPieceGraphics = "Lucena"
        MainBoardRefresh()
    End Sub

    Private Sub mnuThemeDefault_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuThemeDefault.Click
        CurrentPieceGraphics = "Default"
        Try
            Board_Bitmap = New Bitmap(MyPath & "\images\board_1.png")
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
        Try
            Me.BackgroundImage = New Bitmap(MyPath & "\images\ui_blackwhite.png") 'Set the Background image 
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
        MainBoardRefresh()
        Me.Refresh()
    End Sub

    Private Sub mnuThemeBlackWhite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuThemeBlackWhite.Click
        CurrentPieceGraphics = "Maya"
        Try
            Board_Bitmap = New Bitmap(MyPath & "\images\board_5.png")
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
        Try
            Me.BackgroundImage = New Bitmap(MyPath & "\images\ui_metal.png") 'Set the Background image 
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
        MainBoardRefresh()
        Me.Refresh()
    End Sub

    Private Sub mnuThemeSumidhi_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuThemeSumidhi.Click
        CurrentPieceGraphics = "Sumidhi"
        Try
            Board_Bitmap = New Bitmap(MyPath & "\images\board_3.png")
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
        Try
            Me.BackgroundImage = New Bitmap(MyPath & "\images\ui_rainbow.png") 'Set the Background image 
        Catch
            MsgBox("Some Error Occur During Loading of Background")
        End Try
        MainBoardRefresh()
        Me.Refresh()
    End Sub

End Class